import React, { Component } from 'react';
import { StyleSheet, View } from 'react-native';
import { Provider as ThemeProvider } from '@ant-design/react-native';
import { Toast, YiButton, YiEmpty } from '~/components';
import { DefaultStyles } from '~/styles/GlobalStyles';
import { adapt } from '~/utils/ScreenAdapter';

class ErrorBoundary extends Component {
  constructor(props) {
    super(props);
    this.state = {
      error: false,
    };
  }

  static getDerivedStateFromError(error) {
    return { error: true };
  }

  componentDidCatch(error, errorInfo) {
    Toast.fail(error.message);
  }

  restartApp = () => {
    this.props.onAppRestart();
    this.setState({ error: false });
  };

  render() {
    if (this.state.error) {
      return (
        <View style={styles.container}>
          <YiEmpty title="发生未知错误！" />
          <View style={{ alignItems: 'center', marginTop: adapt(40) }}>
            <YiButton
              title={'重启App'}
              style={styles.noContentEditCar}
              onPress={this.restartApp}
            />
          </View>
        </View>
      );
    }
    return <ThemeProvider>{this.props.children}</ThemeProvider>;
  }
}

const styles = StyleSheet.create({
  container: {
    width: '100%',
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingBottom: 150,
  },
  noContentEditCar: {
    width: adapt(140),
    height: adapt(48),
    backgroundColor: DefaultStyles.ThemeColor,
  },
});

export default ErrorBoundary;
